import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权
import Layout from "./views/layout/Layout";
const whiteList = ['/login'] // 不重定向白名单
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({path: '/'})
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.roles.length === 0) {
        await store.dispatch('GetInfo').then(res => { // 拉取用户信息
          if (store.getters.menus.length < 1) {
            global.antRouter = []
            next()
          }
          const menus = filterAsyncRouter(store.getters.menus) // 1.过滤路由
          console.log("信息");
          console.log(menus);

          router.addRoutes(menus) // 2.动态添加路由
          global.antRouter = menus // 3.将路由数据传递给全局变量，做侧边栏菜单渲染工作

          next({
            ...to,
            replace: true
          })
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err.message || '验证失败，请重新登录！')
            next({path: '/'})
          })
        })

      } else {
        next()
      }
    }

  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

/*router.afterEach(() => {
  NProgress.done() // 结束Progress
})*/
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
// // 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = _import(route.component) // 导入组件
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}
